<template>
  <a-space>
    <a-space-compact block>
      <!-- 下拉框 -->
      <a-select v-model:value="selectedOption" :options="TIME_RANGE_PRESETS" @change="handleOptionChange" :field-names="{ value: 'key' }" placeholder="请选择" style="width: 90px" />

      <!-- 时间范围选择器 -->
      <a-range-picker style="width: 240px" v-model:value="localValue" :placeholder="['开始日期', '结束日期']" @change="handleRangeChange" :valueFormat="valueFormat" />
    </a-space-compact>
  </a-space>
</template>

<script setup>
import _ from 'lodash'
import { TIME_RANGE_PRESETS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import { useAppConfigStore } from '@/store/modules/app-store'
const appConfigStore = useAppConfigStore()
// 定义 props 和 emits
const props = defineProps({
  value: {
    type: Array,
    default: () => DEFAULT_TIME_RANGE.value
  }
})
const emit = defineEmits(['update:value', 'search'])
// 主题色
const themeColor = ref(appConfigStore.$state.primaryColor)

watch(appConfigStore, (newValue) => {
  themeColor.value = newValue.$state.primaryColor
})

// 定义日期格式
const valueFormat = 'YYYY-MM-DD'

// 定义下拉框的选中值
const selectedOption = ref(TIME_RANGE_PRESETS.find((item) => _.isEqual(item.value, props.value)))

// 定义本地值，用于 v-model 绑定
const localValue = computed({
  get() {
    return props.value
  },
  set(val) {
    emit('update:value', val)
    if (selectedOption.value !== 'custom') emit('search')
  }
})

// 处理下拉框选项变化
const handleOptionChange = (value) => {
  const time = TIME_RANGE_PRESETS.find((item) => item.key === value).value
  localValue.value = time
}

// 处理时间范围选择器变化
const handleRangeChange = (range) => {
  const time = _.find(TIME_RANGE_PRESETS, (item) => _.isEqual(item.value, range))
  selectedOption.value = time?.key ?? 'custom'
}
watch(
  () => props.value,
  (val) => {
    handleRangeChange(val)
  },
  {
    deep: true
  }
)
</script>
<style lang="css" scoped>
:deep .ant-select-single .ant-select-selector {
  /* color: #1677ff; */
  color: v-bind(themeColor);
}
</style>
